package com.example.xutils1;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.Handler;
import android.os.Message;

public class NetWortUtils {

	public interface OnRequestResultListener {
		public void onSuccess(String result);
	}

	public static void request(final String path, final OnRequestResultListener l) {

		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				String result = (String) msg.obj;
				l.onSuccess(result);
			}
		};

		new Thread() {
			public void run() {
				try {
					URL url = new URL(path);

					HttpURLConnection conn = (HttpURLConnection) url.openConnection();

					conn.setRequestMethod("GET");
					conn.setReadTimeout(25000);
					conn.setConnectTimeout(25000);

					// 鏂偣涓嬭浇鐨勬敮鎸�
					// conn.setRequestProperty("Range", "bytes=2444-")

					int code = conn.getResponseCode();

					if (code == 200) {

						InputStream is = conn.getInputStream();
						ByteArrayOutputStream bos = new ByteArrayOutputStream();

						byte[] tmp = new byte[4086];
						int len = 0;

						while ((len = (is.read(tmp))) != -1) {
							bos.write(tmp, 0, len);
						}

						Message.obtain(handler, 0, bos.toString()).sendToTarget();

						is.close();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			};
		}.start();
	}
}